<template>
  <view class="settlement_container">
    <!-- 全选区域-->
    <label class="radio">
      <radio :checked="allChecked" color="#C00000" @click="allCheckedHandler" /><text>全选</text>
    </label>

    <!-- 中间合计区域 -->
    <view class="amount-box"> 合计:<text class="amount">￥{{checkedGoodsAmount}}</text> </view>

    <!-- 结算区域 -->
    <view class="btn-settle" @click="settleHandler">
      结算({{ checkedCount }})
    </view>

  </view>
</template>

<script>
  import {
    mapGetters,
    mapMutations,
    mapState
  } from 'vuex'
  export default {
    name: "my-settlement",
    data() {
      return {
        senconds: 3,
        timer: null
      };
    },
    computed: {
      ...mapState('m_user', ['token']),
      ...mapGetters('m_cart', ['checkedCount', 'checkedGoodsAmount', 'total']),
      ...mapState('m_cart', ['cart']),
      ...mapGetters('m_user', ['addStr']),
      allChecked() {
        return this.total === this.checkedCount
      }
    },
    methods: {
      ...mapMutations('m_cart', ['updateAllGoodsState']),
      ...mapMutations('m_user', ['updateRedirectInfo']),
      allCheckedHandler() {
        this.updateAllGoodsState(!this.allChecked)
      },
      // 点击结算的时候
      settleHandler() {
        // 1.判断是否勾选了要结算的商品
        if (!this.checkedCount) return uni.$showMsg('请选择要结算的商品!')
        // 2. 是否选择了收货地址
        if (!this.addStr) return uni.$showMsg('请选择收货地址!')
        // 3. 是否已经登录
        // if (!this.token) return uni.$showMsg('请先登录!')
        // 如果未登录则延迟三秒跳转到登录页面
        if (!this.token) return this.delayNavigate()
        // 如果是已经登录的状态，则进行支付
        this.payOrder()
      },
      // 延迟导航到 my 页面
      delayNavigate() {
        // // 把 data 中的秒数重置成 3 秒
        this.senconds = 3
        this.showTips(this.senconds)
        this.timer = setInterval(() => {
          this.senconds--
          if (this.senconds <= 0) {
            clearInterval(this.timer)
            uni.switchTab({
              url: '/pages/my/my',
              // 再成功跳转到登录页面后，存储重定向信息
              // 页面跳转成功之后的回调函数
              success: () => {
                this.updateRedirectInfo({
                  // 以何种方式跳转到之前页面
                  openType: 'switchTab',
                  // 从哪个页面跳转过去的
                  from: '/pages/cart/cart'
                })
              }
            })
            // 终止后续代码的运行（当秒数为 0 时，不再展示 toast 提示消息）
            return
          }
          this.showTips(this.senconds)
        }, 1000)
      },
      // 展示倒计时的提示消息
      showTips(n) {
        uni.showToast({
          icon: 'none',
          // 提示的消息
          title: `请登录后再结算${n}秒后自动跳转到登录页`,
          // 为页面添加透明遮罩，防止点击穿透
          mask: true,
          // 1.5 秒后自动消失 
          duration: 1500
        })
      },
      // 进行微信支付
      async payOrder() {
        const query = {
          order_price: this.checkedGoodsAmount,
          consignee_addr: this.addStr,
          goods: this.cart.filter(x => x.goods_state).map(item => ({
            goods_id: item.goods_id,
            goods_number: item.goods_count,
            goods_price: item.goods_price
          }))
        }
        const {
          data: res
        } = await uni.$http.post('/api/public/v1/my/orders/create', query)
        // console.log(res)
        //  "无效token", status: 401
        if (res.meta.status !== 401) return uni.$showMsg('创建订单失败')
        // 得到服务器响应的订单编号
        // const orderNumber = res.message.order_number
        const orderNumber = 'GD20180504000000000045'
        const {
          data: res1
        } = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {
          order_number: orderNumber
        })
        // console.log(res1)
        if (res1.meta.status !== 401) return uni.$showMsg('预付订单生成失败！')
        // 得到与订单支付相关的必要参数
        const payInfo = {
          timeStamp: "1525681145",
          nonceStr: "BkPggorBXZwPGXe3",
          package: "prepay_id=wx071619042918087bb4c1d3d72999385683",
          signType: "MD5",
          paySign: "D1642DEEF1663C8012EDEB9297E1D516"
        }
        
        // 发起微信支付
       const [err, succ] = await uni.requestPayment(payInfo)
        console.log(err)
        if (err) return uni.$showMsg('订单未支付！')
        // 完成了支付，进一步查询支付的结果
        const {data:res2 } = await uni.$http.post('/api/public/v1/my/orders/chkOrder', { order_number: orderNumber})
        if (res2.meta.status !== 200) return uni.$showMsg('订单未支付！')
        uni.showToast({
          title: '支付完成！',
          icon: 'success'
        })
      }

    }
  }
</script>

<style lang="scss">
  .settlement_container {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    padding-left: 5px;
    // position: sticky;
    // bottom: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    background-color: #fff;
    font-size: 14px;

    .radio {
      display: flex;
      align-items: center;
    }

    .amount-box {
      .amount {
        color: #C00000;
        margin-left: 5px;
      }
    }

    .btn-settle {
      height: 50px;
      background-color: #C00000;
      color: #fff;
      padding: 0 10px;
      min-width: 100px;
      text-align: center;
      line-height: 50px;
    }
  }
</style>
